/**
 * 旅游攻略模块
 */
const fs = require('fs');
const { getUniqueId } = require('../utils/time');
const { isRequire } = require('../utils/common');
const { paginateArray, PAGE_SIZE } = require('../utils/page');
const { ACTIVE_TYPE } = require('../utils/constant');

// 旅游攻略对象
const travelGuide = {
    id: '',
    title: '',
    content: '',
    address: '',
    createTime: '',
    updateTime: '',
    author: '',
    cover: '',
    category: '', // 种类
    tags: '',
    views: '',
    likes: '',
    comments: '',
    recommend: '',
    top: false, // 是否置顶
    activeType: ACTIVE_TYPE.活动介绍, // 活动类型 ACTIVE_TYPE
}

// 旅游攻略数据文件地址
const filePath = './data/travelGuide.txt';

// 旅游攻略必填字段
const requireKeys = {
    "title": "标题",  
    "content": "内容", 
    "address": "地址", 
    "author": "作者",
    "cover": "封面", 
    "category": "种类",
    "createTime": "创建时间",
    "updateTime": "更新时间",
    "views": "浏览量",
    "likes": "点赞量",
    "top": "置顶",
}

/**
 * 查询所有旅游攻略并返回
 * @returns 
 */
async function readGuide() {
    try {
        const res = await fs.readFileSync(filePath, 'utf-8');
        const data = res.toString();
        // 判断是否有数据
        if (data) {
            const arr = JSON.parse(data);
            return Promise.resolve(arr);
        } else {
            return Promise.resolve([]);
        }
    } catch (error) {
        // 判断是否文件不存在
        if (String(error).indexOf('no such file or directory') !== -1) {
            return Promise.resolve([]);
        }
        return Promise.reject(error);
    }
};

/**
 * 添加旅游攻略
 * @param {*} content 旅游攻略信息
 * @returns 
 */
async function addGuide(content) {
    try {
        const res = await readGuide();
        // 判断商品名称是否重复
        const index = res.findIndex((item) => item.title === content.title);
        if (index > -1) {
            return Promise.reject('该旅游攻略标题已存在');
        }
        const uniqueId = getUniqueId();
        content.id = uniqueId;
        // 当前时间戳
        const timestamp = Math.floor(Date.now() / 1000);
        content.createTime = timestamp;
        content.updateTime = timestamp;
        // 遍历判断是否必填
        let flag = isRequire(requireKeys, content);
        if(!flag){
            return Promise.reject('必填项不完整');
        }
        if (res && Array.isArray(res)) {
            res.unshift(content);
        }
        const data = JSON.stringify(res)
        await fs.writeFileSync(filePath, data);
        return Promise.resolve();
    } catch (error) {
        console.log(error);
        return Promise.reject();
    }
}

/**
 * 分页查询旅游攻略
 * @returns 
 */
async function queryGuide(params) {
    const { pageNum, pageSize, searchParams, type } = params;
    try {
        const res = await fs.readFileSync(filePath, 'utf-8');
        const data = res.toString();
        // 判断是否有数据
        if (data) {
            let arr = JSON.parse(data);
            if(!type){
                const pageResult = paginateArray(arr, pageNum, pageSize ? pageSize : PAGE_SIZE, searchParams )
                return Promise.resolve(pageResult);
            }
            const { guideType, activeType } = type;
            // 根据攻略类型、活动类型筛选
            if (guideType && activeType) {
                arr = arr.filter((item) => item.category === guideType && item.activeType === activeType);
            } else if (guideType) {
                arr = arr.filter((item) => item.category === guideType);
            } else if (activeType) {
                arr = arr.filter((item) => item.activeType === activeType);
            }
            const pageResult = paginateArray(arr, pageNum, pageSize ? pageSize : PAGE_SIZE, searchParams )
            return Promise.resolve(pageResult);
        } else {
            return Promise.resolve([]);
        }
    } catch (error) {
        // 判断是否文件不存在
        if (String(error).indexOf('no such file or directory') !== -1) {
            return Promise.resolve([]);
        }
        return Promise.reject(error);
    }
}

/**
 * 批量修改值
 * @param {*} key 
 * @returns 
 */
async function updateGuide(key) {
    try {
        const res = await readGuide();
        const data = JSON.parse(JSON.stringify(res));
        // 根据key修改值
        for (let i = 0; i < data.length; i++) {
            if (i % 2 === 0) {
                data[i][key] = ACTIVE_TYPE.活动介绍;
            }else{
                data[i][key] = ACTIVE_TYPE.活动安排;
            }
        }
        
        const rs = await fs.writeFileSync(filePath, JSON.stringify(data));
        console.log(rs);
        return Promise.resolve();
    } catch (error) {
        console.log(error);
        return Promise.reject();
    }
}
/**
 * 获取详情
 * @param {*} id 
 */
async function getGuideDetail(id) {
    try {
        const res = await readGuide();
        const data = JSON.parse(JSON.stringify(res));
        const item = data.find((item) => id === item.id);
        return Promise.resolve(item);
    } catch (error) {
        console.log(error);
        return Promise.reject();
    }
}

/**
 * 修改旅游攻略标题、地点、内容
 */
async function updateGuideSomeKey(id, { title, address, content }) {
    try {
        const res = await readGuide();
        const data = JSON.parse(JSON.stringify(res));
        const index = data.findIndex((item) => id === item.id);
        const item = data[index];
        item.title = title;
        item.address = address;
        item.content = content;
        data.splice(index, 1, item);
        await fs.writeFileSync(filePath, JSON.stringify(data));
        return Promise.resolve();
    } catch (error) {
        console.log(error);
        return Promise.reject();
    }
}

module.exports = { 
    readGuide, 
    addGuide,
    queryGuide,
    updateGuide,
    getGuideDetail,
    updateGuideSomeKey
}